package net.synck.gcontacts.handlers;

import java.io.IOException;
import java.util.Iterator;

import net.synck.gcontacts.wizards.MergeWizard;

import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.commands.IHandler;
import org.eclipse.core.commands.IHandlerListener;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.handlers.HandlerUtil;
import org.eclipse.ui.internal.dialogs.DialogUtil;

import com.google.gdata.data.contacts.ContactEntry;
import com.google.gdata.util.ServiceException;

public class DeleteContactHandler extends AbstractHandler {

	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {
		
		IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindow(event);
		MergeWizard wizard = new MergeWizard();
		ISelection selection = HandlerUtil.getActiveWorkbenchWindow(event)
			.getActivePage().getSelection();
		
		if (selection != null & selection instanceof IStructuredSelection) {
			IStructuredSelection strucSelection = (IStructuredSelection) selection;
			
			if (!strucSelection.isEmpty()) {
				if (!MessageDialog.openConfirm(window.getShell(), "Confirm", 
						"Are you sure you want to delete " + strucSelection.size() + " contact(s)" ))
					return null;
			}
			
			try {
				
			for (Iterator iterator = strucSelection.iterator(); iterator.hasNext();) {
				Object element = (Object) iterator.next();
				if (element instanceof ContactEntry) {
					ContactEntry contact = (ContactEntry)element;				
						contact.delete();				
				}
			}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ServiceException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		
		}
		
		
		return null;
		
	}


}
